import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import styleImport from 'vite-plugin-style-import'
import legacy from '@vitejs/plugin-legacy'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

// https://vitejs.dev/config/
export default ({ mode }) => {
    return defineConfig({
        base: '/',
        resolve: {
            alias: {
                '@': resolve('src')
            }
        },
        server: {
            host: '0.0.0.0',
            port: 8088
        },
        css: {
            postcss: {
                plugins: [
                    {
                        postcssPlugin: 'internal:charset-removal',
                        AtRule: {
                            charset: (atRule) => {
                                if (atRule.name === 'charset') {
                                    atRule.remove();
                                }
                            }
                        }
                    }
                ]
            },
            preprocessorOptions: {
                scss: {
                    additionalData: '@import "@/assets/style/index.scss";'
                }
            }
        },
        plugins: [
            vue(),
            Components({
                extensions: ['vue'],
                deep: true,
                directoryAsNamespace: true,
                dts: mode === 'development' ? 'src/components.d.ts' : '',
                resolvers: [ElementPlusResolver()]
            }),
            styleImport({
                libs: [
                    {
                        libraryName: 'element-plus',
                        esModule: true,
                        resolveStyle: name => {
                            return `element-plus/theme-chalk/${name}.css`
                        }
                    }
                ]
            }),
            legacy({
                targets: ['chrome 52', 'ie >= 11'],
                additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
                polyfills: ['es.promise.finally', 'es/map', 'es/set'],
                modernPolyfills: ['es.promise.finally']
            }),
            VueSetupExtend()
        ],
        build: {
            assetsDir: 'assets',
            chunkSizeWarningLimit: 1000,
            rollupOptions: {
                output: {
                    manualChunks(id) {
                        if(id.includes('node_modules')){
                            return id.toString().split('node_modules/')[1].split('/')[0].toString()
                        }
                    }
                }
            }
        }
    })
}
